<template>
  <div class="users">
    <!-- 面包屑组件 -->
    <Breadcrumb name1="用户管理" name2="用户列表"></Breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 搜索与添加区域 -->
          <el-input
            placeholder="请输入邮箱"
            v-model="email"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserByEmail"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 添加用户区域 -->
          <el-button type="primary" @click="addDialogVisible = true"
            >用户添加</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userList" stripe style="width: 100%" border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="头像">
          <template slot-scope="scope">
            <img :src="scope.row.img" style="width: 50px; height: 50px" />
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="注册时间">
          <template slot-scope="scope">
            <span>{{ scope.row.datatime | formatDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="权限">
          <template slot-scope="scope">
            <span>{{ Number(scope.row.power) ? '管理员' : '普通用户' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="0"
              @change="userStatusChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="removeUserById(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <Paging :paging="paging" @change="changepage"></Paging>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDislogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        label-width="70px"
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="addForm.email"
            placeholder="请输入真实邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="addForm.pwd" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="头像url" prop="img">
          <el-input
            v-model="addForm.img"
            placeholder="请输入正确的url图片地址,此项可不填"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户"
      @close="aditClosed"
      :visible.sync="editDialogVisble"
      width="50%"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="id" prop="id">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像Url" prop="img">
          <el-input v-model="editForm.img"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisble = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Breadcrumb from '@/components/breadcrumb'
import Paging from '@/components/paging'
import { Message } from 'element-ui'
import {
  getUserList,
  getUserByEmail,
  updateUserStatus,
  addUser,
  deleteUser,
  getUserById,
  updateUser,
  isExist,
} from '@/api'
export default {
  data() {
    var checkImgUrl = (rule, value, callback) => {
      if (!value) {
        callback()
      } else {
        const regUrl =
          /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
        if (regUrl.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的url图片地址'))
        }
      }
    }
    var checkEmail = (rule, value, callback) => {
      if (!value) {
        callback()
      } else {
        isExist(value).then((res) => {
          if (res.data.code == 0) {
            callback()
          } else {
            callback(new Error('邮箱已存在'))
          }
        })
      }
    }
    return {
      userList: [],
      paging: {
        page: 1,
        limit: 5,
        total: 0,
      },
      email: '',
      // 控制用户对话框的显示和隐藏
      addDialogVisible: false,
      // 添加用户数据的对象
      addForm: {
        email: '',
        pwd: '',
        img: '',
      },
      addFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '请输入6-18位密码', trigger: 'blur' },
        ],
        img: [{ validator: checkImgUrl, trigger: 'blur' }],
      },
      // 控制修改用户信息对话框的显示和隐藏
      editDialogVisble: false,
      editForm: {
        id: '',
        email: '',
        img: '',
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' },
        ],
        img: [{ validator: checkImgUrl, trigger: 'blur' }],
      },
    }
  },
  components: {
    Breadcrumb,
    Paging,
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await getUserList({
        page: this.paging.page,
        limit: this.paging.limit,
      })
      if (res.code === 1) {
        this.userList = res.data
        this.paging.total = res.total[0].total
        Message.success(res.msg)
      } else {
        Message.error(res.msg)
      }
    },
    async getUserByEmail() {
      if (!this.email) {
        Message.error('请输入内容')
        return
      }
      const { data: res } = await getUserByEmail({
        email: this.email,
        page: this.paging.page,
        limit: this.paging.limit,
      })
      if (res.code === 1) {
        this.userList = res.data
        this.paging.total = res.total
        Message.success(res.msg)
      } else {
        Message.error(res.msg)
      }
    },
    async userStatusChanged(row) {
      if (row.power == 1) {
        return Message.error('管理员不能修改状态')
      }
      const { data: res } = await updateUserStatus({
        id: row.id,
        status: row.status,
      })
      if (res.code == 1) {
        Message.success(res.msg)
      } else {
        Message.error(res.msg)
      }
    },
    changepage(page) {
      this.paging.page = page
      this.getUserList()
    },
    // 监听添加用户的对话框关闭事件
    addDislogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          if (this.addForm.img == '' || !this.addForm.img) {
            this.addForm.img =
              'http://api.btstu.cn/sjtx/api.php?lx=b1&format=images'
          }
          const { data: res } = await addUser(this.addForm)
          if (res.code === 1) {
            Message.success(res.msg)
            this.addDialogVisible = false
            this.getUserList()
          } else {
            Message.error(res.msg)
          }
        }
      })
    },
    //  根据id删除用户
    removeUserById(row) {
      if (row.power == 1) {
        return Message.error('管理员不能删除')
      }
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await deleteUser({ id: row.id })
          if (res.code == 1) {
            Message.success(res.msg)
            this.getUserList()
          } else {
            Message.error(res.msg)
          }
        })
        .catch(() => {
          Message.info('已取消删除')
        })
    },
    // 修改用户信息
    async showEditDialog(id) {
      const { data: res } = await getUserById({ id })
      this.editForm = res.data[0]
      this.editDialogVisble = true
    },
    // 监听修改用户对话框的关闭事件
    aditClosed() {
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await updateUser(this.editForm)
          if (res.code == 1) {
            Message.success(res.msg)
            this.editDialogVisble = false
            this.getUserList()
          } else {
            Message.error(res.msg)
          }
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.el-table {
  margin-top: 15px;
  margin-bottom: 10px;
}
</style>
